package com.wy.util;

import com.sun.org.apache.regexp.internal.RE;
import com.wy.vo.DueItem;
import com.wy.vo.LoanItem;
import com.wy.vo.OverDueLoanItem;
import com.wy.vo.PersonalLoan;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * Created by wy on 2017/11/2.
 * XML解析工具包
 */
public class RecommendUtils {
    /**获取网页xml转换成str*/
    public static String getXmlString(String url) throws Exception {

        try {
            HttpClient client = new DefaultHttpClient();

            HttpGet httpget = new HttpGet(
                    url);
            httpget.setHeader("Accept",
                    "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8");
            httpget.setHeader("Accept-Encoding", "gzip, deflate");
            httpget.setHeader("Accept-Language", "zh-CN,zh;q=0.8");
            httpget.setHeader("Pragma", "no-cache");
            httpget.setHeader("Upgrade-Insecure-Requests", "1");
            httpget.setHeader("User-Agent",
                    "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36");
            httpget.setHeader("Cache-Control", "no-cache");

            HttpResponse response = client.execute(httpget);
            int status = response.getStatusLine().getStatusCode();
            String entityStr = EntityUtils.toString(response.getEntity(),"UTF-8");
            if (status != 200) {
                throw new RuntimeException(String.format("api return error http code %d, detail: \n%s", status,entityStr));
            }

            //readStringXML2(entityStr);
            //getPersonLoanList(entityStr);
            return entityStr;
        } catch (Exception t) {
            String msg = String.format("Failed to call api '%s'", t.getCause());

            throw t;
        }
    }

    private static void readStringXML2(String strXml) throws DocumentException {
        Document document = DocumentHelper.parseText(strXml);
        SAXReader reader = new SAXReader();
        Element root =document.getRootElement();
        Iterator<Element> it = root.elementIterator();
        String name;
        Element e;
        while (it.hasNext()){
            e = it.next();
            name = e.getName();
            Element id = e.element(name + "-id");
            if (id != null){
                System.out.println(id.getText());
            }
        }

    }
    /**
     *返回个人借书信息
     * */
    public static PersonalLoan getPersonLoan(String xmlStr) throws DocumentException {
        //根据String 生成Document对象
        Document document = DocumentHelper.parseText(xmlStr);
        Element root =document.getRootElement();
        PersonalLoan personalLoan = new PersonalLoan();
        personalLoan.setBorName(root.elementText("bor-name"));
        personalLoan.setTotalLoan(root.elementText("total-loan-records"));
        personalLoan.setDisplayLoan(root.elementText("display-records"));
        personalLoan.setSessionId(root.elementText("session-id"));
        //获取根元素下名为"loan-item"的标签列表
        List<Element> list = root.elements("loan-item");
        LoanItem loanItem;
        /**返回给PersonalLoan的List*/
        ArrayList<LoanItem> loanList = new ArrayList<LoanItem>();
        for (Element e : list){
            loanItem = new LoanItem();
            loanItem.setDocNo(e.elementText("doc-number"));
            loanItem.setTitle(e.elementText("z13-title"));
            loanItem.setAuthor(e.elementText("z13-author"));
            loanItem.setPublisher(e.elementText("z13-publisher"));
            loanItem.setYear(e.elementText("z13-year"));
            loanItem.setISBN(e.elementText("z13-isbn-issn"));
            loanItem.setCallNo(e.elementText("call-no"));
            loanItem.setDueDate(e.elementText("due-date"));
            loanItem.setDueHour(e.elementText("due-hour"));
            loanItem.setReturnedDate(e.elementText("returned-date"));
            loanItem.setReturnedHour(e.elementText("returned-hour"));
            loanItem.setSubLibrary(e.elementText("sub-library"));
            loanList.add(loanItem);
        }
        personalLoan.setLoanList(loanList);
        return personalLoan;
    }
    /**用于解析超期借书信息XML*/
    public static OverDueLoanItem getOverDue(String xmlStr) throws DocumentException {
        Document document = DocumentHelper.parseText(xmlStr);
        Element root =document.getRootElement();
        OverDueLoanItem overDueLoanItem = new OverDueLoanItem();
        overDueLoanItem.setSeesionId(root.elementText("session-id"));
        overDueLoanItem.setTotalLoanRecords(root.elementText("total-loan-records"));
        List<Element> list = root.elements("loan-item");
        DueItem dueItem;
        ArrayList<DueItem> dueItems = new ArrayList<DueItem>();
        for (Element element : list){
            dueItem = new DueItem();
            dueItem.setBorId(element.elementText("bor-id"));
            dueItem.setBorName(element.elementText("bor-name"));
            dueItem.setTitle(element.elementText("title"));
            dueItem.setCallNo(element.elementText("call-no"));
            dueItem.setDueDate(element.elementText("due-date"));
            dueItem.setDueHour((element.elementText("due-hour")));
            dueItems.add(dueItem);
        }
        overDueLoanItem.setDueItems(dueItems);
        return overDueLoanItem;
    }
}
